#include <SDL2/SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;

int main(int argc, char **argv)
{
    if (SDL_Init(SDL_INIT_VIDEO) == -1) {
        printf("SDL Init Error %d\n", (int)SDL_GetError());
        return 1;
    }

    SDL_Window *window = SDL_CreateWindow("Hello World!",
                                          SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                          SCREEN_WIDTH, SCREEN_HEIGHT,
                                          SDL_WINDOW_SHOWN);
    if (window == NULL) {
        printf("SDL CreateWindow Error %d\n", (int)SDL_GetError());
        return 1;
    }

    SDL_Surface *surface = SDL_GetWindowSurface(window);
    SDL_Surface *image = SDL_LoadBMP("cat.bmp");

    SDL_Rect rect;
    rect.x = 400;
    rect.y = 300;
    int i;
    SDL_BlitSurface(image, NULL, surface, &rect);

    /*for (i=0; i<3; i++)
    {
        SDL_BlitSurface(image, NULL, surface, &rect);
        rect.x = rect.x + 250;
    }*/

    SDL_UpdateWindowSurface(window);

    SDL_Event event;
    bool quit = false;

    while (quit == false) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT)
                quit = true;
            //else if (event.type == SDL_MOUSEMOTION)
                //printf("Hello world\n");
            else if (event.type == SDL_MOUSEBUTTONDOWN) {
                if (event.button.button == SDL_BUTTON_LEFT)
                    printf("Left\n");
                else if (event.button.button == SDL_BUTTON_RIGHT)
                    printf("Right\n");
            }
            else if (event.type == SDL_KEYDOWN)
            {
                SDL_FillRect(surface, &rect, 0);
                if (event.key.keysym.sym == SDLK_UP)
                {
                    printf("Up\n");
                    rect.y = rect.y - 10;
                    if (rect.y < 0)
                        rect.y = 0;
                }
                else if (event.key.keysym.sym == SDLK_DOWN)
                {
                    printf("Down\n");
                    rect.y = rect.y + 10;
                }
                else if (event.key.keysym.sym == SDLK_LEFT)
                {
                    printf("Left\n");
                    rect.x = rect.x - 10;
                    if (rect.x < 0)
                        rect.x = 0;
                }
                else if (event.key.keysym.sym == SDLK_RIGHT)
                {
                    printf("Righ\n");
                    rect.x = rect.x + 10;
                }

                //SDL_FillRect(surface, NULL, 0);
                SDL_BlitSurface(image, NULL, surface, &rect);
            }

            SDL_UpdateWindowSurface(window);
        }
    }

    SDL_FreeSurface(image);
    SDL_FreeSurface(surface);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
